package happy.robot;

import happy.robot.constant.CustomerConstants;
import happy.robot.constant.ResponseConstants;
import happy.robot.entity.Customer;
import happy.robot.mapper.CustomerMapper;
import happy.robot.mapper.RemarkMapper;
import happy.robot.vo.ResponseVo;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Pattern;


/**
 * Created by wang on 17-11-19.
 */

@RestController
public class CustomerController {


    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private RemarkMapper remarkMapper;

    private final Pattern PATTERN_PHONE_NUMBER = Pattern.compile("^[1][43578][]0-9]{9}$");



    @RequestMapping(value = "/customer/save", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_VALUE})
    public String save(@RequestBody String body) {
        JSONObject bodyJson = JSONObject.fromObject(body);
        ResponseVo responseVo = new ResponseVo();
        List<String> errorMsgs = new LinkedList<>();
        Customer customer = new Customer();
        Object parentName = bodyJson.get("parentName");
        Object phoneNumber = bodyJson.get("phoneNumber");
        Object childName = bodyJson.get("childName");
        Object childSex = bodyJson.get("childSex");
        Object childAge = bodyJson.get("childAge");
        Object childSchool = bodyJson.get("childSchool");
        Object address = bodyJson.get("address");
        Object chargePerson = bodyJson.get("chargePerson");
        Object chargeBill = bodyJson.get("chargeBill");
        Object closePerson = bodyJson.get("closePerson");
        Object birthDate = bodyJson.get("birthDate");
        Object appointTime = bodyJson.get("appointTime");
        Object remark = bodyJson.get("remark");
        this.log(parentName, phoneNumber, childName, childSex, childAge, childSchool, address, chargePerson, chargeBill, closePerson, birthDate, appointTime, remark);
        customer.setParentName(parentName != null ? parentName.toString() : StringUtils.EMPTY);
        customer.setPhoneNumber(phoneNumber != null ? phoneNumber.toString() : StringUtils.EMPTY);
        customer.setChildName(childName != null ? childName.toString() : StringUtils.EMPTY);
        customer.setChildSex(childSex != null ? childSex.toString() : StringUtils.EMPTY);
        customer.setChildAge(Integer.parseInt(childAge != null && !childAge.toString().isEmpty()? childAge.toString() : "0"));
        customer.setChildSchool(childSchool != null ? childSchool.toString() : StringUtils.EMPTY);
        customer.setAddress(address != null ? address.toString() : StringUtils.EMPTY);
        customer.setChargePerson(chargePerson != null ? chargePerson.toString() : StringUtils.EMPTY);
        customer.setChargeBill(chargeBill != null ? chargeBill.toString() : StringUtils.EMPTY);
        customer.setClosePerson(closePerson != null ? closePerson.toString() : StringUtils.EMPTY);
        try {
            customer.setBirthDate(birthDate != null ? CustomerConstants.DATE_FORMAT.parse(birthDate.toString()) : new Date());
            customer.setAppointTime(appointTime != null ? CustomerConstants.DATE_FORMAT.parse(appointTime.toString()) : new Date());
        } catch (ParseException e) {
            errorMsgs.add("1");
        }
        customer.setRemark(remark != null ? remark.toString() : StringUtils.EMPTY);
        if (StringUtils.isBlank(customer.getParentName())){
            errorMsgs.add("2");
        }
        if (StringUtils.isBlank(customer.getPhoneNumber()) || !PATTERN_PHONE_NUMBER.matcher(customer.getPhoneNumber()).matches()){
            errorMsgs.add("3");
        }
        if (StringUtils.isBlank(customer.getChargePerson())){
            errorMsgs.add("4");
        }
        if (errorMsgs.isEmpty()) {
            customerMapper.insertCustomer(customer);
            responseVo.setStatus(ResponseConstants.RESULT_OK);
        } else {
            responseVo.setStatus(ResponseConstants.RESULT_ERR);
            responseVo.setMessages(errorMsgs);
        }
        return JSONObject.fromObject(responseVo).toString();
    }

    @RequestMapping(value = "/customer/update", method = RequestMethod.PUT, produces = {MediaType.APPLICATION_JSON_VALUE})
    public String update(@RequestBody String body) {
        ResponseVo responseVo = new ResponseVo();
        try {
            JSONObject bodyJson = JSONObject.fromObject(body);
            Object requestId = bodyJson.get("id");
            Object requestRemark = bodyJson.get("remark");
            Object requestNewRemark = bodyJson.get("newRemark");
            Long id = Long.parseLong(requestId.toString());
            String remark = requestRemark.toString();
            String newRemark = requestNewRemark.toString();
            customerMapper.updateRemark(id, newRemark);
            remarkMapper.insert(id, remark);
            responseVo.setStatus(ResponseConstants.RESULT_OK);
        } catch (RuntimeException e) {
            responseVo.setStatus(ResponseConstants.RESULT_ERR);
        }
        return JSONObject.fromObject(responseVo).toString();
    }

    /**
     * 打印日志
     * @param parentName
     * @param phoneNumber
     * @param childName
     * @param childSex
     * @param childAge
     * @param childSchool
     * @param address
     * @param chargePerson
     * @param chargeBill
     * @param closePerson
     * @param remark
     */
    private void log(Object parentName, Object phoneNumber, Object childName, Object childSex, Object childAge, Object childSchool, Object address, Object chargePerson, Object chargeBill, Object closePerson, Object birthDate, Object appointTime, Object remark) {
        log.info("parentName = " + parentName);
        log.info("phoneNumber = " + phoneNumber);
        log.info("childName = " + childName);
        log.info("childSex = " + childSex);
        log.info("childAge = " + childAge);
        log.info("childSchool = " + childSchool);
        log.info("address = " + address);
        log.info("chargePerson = " + chargePerson);
        log.info("chargeBill = " + chargeBill);
        log.info("closePerson = " + closePerson);
        log.info("birthDate = " + birthDate);
        log.info("appointTime = " + appointTime);
        log.info("remark = " + remark);
    }

}
